/*
 * File: StoneMasonKarel.java
 * --------------------------
 * The StoneMasonKarel subclass as it appears here does nothing.
 * When you finish writing it, it should solve the "repair the quad"
 * problem from Assignment 1.  In addition to editing the program,
 * you should be sure to edit this comment so that it no longer
 * indicates that the program does nothing.
 */

import stanford.karel.*;

public class StoneMasonKarel extends SuperKarel {
	/* Rebuilds all the available columns, while there are any and Karel doesn't hit the wall 
	 * Preconditions: Karel is at the bottom left position
	 * Postconditions: Karel is at the botom right corner and all columns are fixed
	 */
	public void run(){
		/* always try to rebuild the first column */
		rebuildColumn();
		
		/* while Karel finds columns to rebuild ... */
		while(frontIsClear()){ 
			moveToNextColumn();
			/* ...rebuild column */
			rebuildColumn();	
		}
	}
	
	/*
	 * Goes all the way up the column reconstructing it
	 *
	 * Precondition: Karel is positioned at the bottom of a column looking East
	/* Postcondition: Karel is position at the bottom of a fixed column, looking East */ 
	private void rebuildColumn(){
		turnLeft();
		
		/* reconstruct the first part */
		reconstruct();
		
		/* and continue reconstructing until the top of the column is reached */
		while(frontIsClear()){
			move();
			reconstruct();
		}
		
		/* finally go back down to the floor facing East */
		goBackToFloor();
	}
	
	/*
	 *  Karel moves to the next column
	 *  If there are no more columns left a !COLUMNS_FOUND will be returned
	 */
	private void moveToNextColumn(){
		for(int i=0; i<4; i++)
		{
			move();
		}
		
	}
	
	/*
	 *  Karel goes all the way down back to the floor and ends up facing east
	 *  Preconditions: Karel is looking north and ceiling was reached
	 *  Postconditiosn: Karel is positioned at the floor and is looking East
	 */
	private void goBackToFloor(){
		turnAround();
		while(frontIsClear()){
			move();
		}
		
		turnLeft();
	}
	
	/*
	 *  Rebuilds a part of the column, if needed
	 */
	private void reconstruct(){
		if (!beepersPresent()){
			putBeeper();
		}
	}
}
